//
//  iphone_test2ViewController.m
//  iphone_test2
//
//  Created by Yang Lu on 3/31/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "CarpoolWithFriendsAdapter.h"
#import "CarpoolWithFriendsServer.h"
#import "CarpoolWithFriendsAppDelegate.h"
#import "StreamFirstLevelViewController.h"
#import "MenusViewController.h"
#import "RevealController.h"

#import <QuartzCore/QuartzCore.h>

@interface LoginViewController()
    //private properties
    
    //private methods
- (void)btnRegisterPressed:(id)sender;
-(void)setViewMovedUp:(BOOL)movedUp;
-(void)switchToMainStreamView;
@end

@implementation LoginViewController

@synthesize btnLogin;
@synthesize loginTable;

//hardcoded right now
#define kMin 150
#define MOVEUP_OFFSET -100
#define STATUSBAR_HEIGHT 0


- (IBAction)backgroundTap:(id)sender{
    [tfEmail resignFirstResponder];
    [tfPassword resignFirstResponder];
}

- (void)btnLoginPressed:(id)sender{
	//trim  the input strings
    NSString *trimmedEmail= [tfEmail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *trimmedPassword= [tfPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if([trimmedEmail isEqualToString:@""] == YES
       || [trimmedPassword isEqualToString:@""] == YES)
    {
        UIAlertView *inputError = [[UIAlertView alloc] initWithTitle:@"Input Error" 
                                                                    message:@"Email or Password is invalid"
                                                                   delegate:self cancelButtonTitle:@"Ok"
                                                                    otherButtonTitles:nil];
        [inputError show];
        [inputError release];
        
        return;
    }
    
    NSMutableDictionary *retDict;
    BOOL retVal = [CarpoolWithFriendsAdapter requestLoginWithEmail:trimmedEmail password:trimmedPassword retData:&retDict];
    
    if(retVal == YES)
    {
        // save user login info in NSUserDefaults
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:trimmedEmail forKey:@"userEmail"];
        [defaults setObject:trimmedPassword forKey:@"userPassword"];
        [defaults setBool:YES forKey:@"loginBefore"];
        [defaults setObject:[retDict objectForKey:@"uid"] forKey:@"uid"];        
        [defaults synchronize];
        // store the info transferred from server into NSUserDefaults
        //....
         
        [self switchToMainStreamView];
    }
    else
    {
        UIAlertView *loginFailureError = [[UIAlertView alloc] initWithTitle:@"Login Failure" 
                                                                    message:@"Wrong Email or Password"
                                                                   delegate:self cancelButtonTitle:@"Ok"
                                                          otherButtonTitles:nil];
        [loginFailureError show];
        [loginFailureError release];
    }
	
}

-(void)switchToMainStreamView
{
    // switch to stream view
    CarpoolWithFriendsAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];        
    StreamFirstLevelViewController *streamViewController = [[StreamFirstLevelViewController alloc] init];
    MenusViewController *menusViewControler = [[MenusViewController alloc] init];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController: streamViewController];
    RevealController *revealController = [[RevealController alloc] initWithFrontViewController:navigationController rearViewController:menusViewControler];
    appDelegate.window.rootViewController = revealController;
    [navigationController release];
    [streamViewController release];
    [menusViewControler release];
    [revealController release];
    
    // add animation
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:appDelegate.window cache:YES];
    [self.navigationController.view removeFromSuperview];
    
    [UIView commitAnimations];

}

- (void)btnRegisterPressed:(id)sender{
    RegisterViewController *regViewController = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:regViewController animated:YES];
    
	[regViewController release];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.btnLogin.layer.cornerRadius = 10; // this value vary as per your desire
    self.btnLogin.clipsToBounds = YES;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
	[tfEmail release];
	[tfPassword release];
    [currTextField release];
    
    
    
    [btnLogin release];
    [loginTable release];
    
    [super dealloc];
}

//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // if you want to slide up the view
    
    CGRect rect = self.view.frame;
    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y = MOVEUP_OFFSET;//kMin - currTextField.frame.origin.y ;
    }
    else
    {
        // revert back to the normal state.
        rect.origin.y = STATUSBAR_HEIGHT;
    }
    self.view.frame = rect;
    
    [UIView commitAnimations];
}

- (void)keyboardWillShow:(NSNotification *)notif
{
    //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately
    NSLog(@"%d", [currTextField isFirstResponder] );
    if ([currTextField isFirstResponder] && currTextField.frame.origin.y + self.view.frame.origin.y >= kMin)
    {
        [self setViewMovedUp:YES];
    }
    else if (![currTextField isFirstResponder] && currTextField.frame.origin.y  + self.view.frame.origin.y < kMin)
    {
        [self setViewMovedUp:NO];
    }
}

- (void)keyboardWillHide:(NSNotification *)notif
{
    //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately
    if (self.view.frame.origin.y < 0 ) {
        [self setViewMovedUp:NO];
    }
}

#pragma mark - Text Field Delegate

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
    if (currTextField) {
        [currTextField release];
    }
    currTextField = [sender retain];
    
    //move the main view, so that the keyboard does not hide it.
    //if (self.view.frame.origin.y + currTextField.frame.origin.y >= kMin) {
//    NSLog(@"self.view.frame.origin.y:%f", self.view.frame.origin.y );
//    NSLog(@"frame.origin.y:%f", currTextField.frame.origin.y );
    [self setViewMovedUp:YES];    
    //}
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // clear the background of table view
    loginTable.backgroundColor = [UIColor clearColor];
    loginTable.opaque = NO;
    
    // Check if we have a revealButton already.
    if (![self.navigationItem rightBarButtonItem])
    {
        // If not, allocate one and add it.
        UIBarButtonItem *registerButton = [[UIBarButtonItem alloc] initWithTitle:@"Sign Up" style:UIBarButtonItemStylePlain target:self action:@selector(btnRegisterPressed:)];
        self.navigationItem.rightBarButtonItem = registerButton;
        [registerButton release];
    }

    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification object:self.view.window]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification object:self.view.window];
}

- (void)viewWillDisappear:(BOOL)animated
{
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; 
}

#pragma mark - Table view data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        // set textfield
        if(indexPath.row == 0)
        {
            tfEmail = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 200, 35)];
            tfEmail.tag = 0;
            tfEmail.placeholder = @"email";
            tfEmail.delegate = self;
            
            [cell.contentView addSubview:tfEmail];
        }
        else
        {
            tfPassword = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 200, 35)];
            tfPassword.tag = 1;
            tfPassword.placeholder = @"password";
            
            tfPassword.delegate = self;
            [cell.contentView addSubview:tfPassword];
        }
    }
    
    return cell;
}

@end
